﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Newtonsoft.Json.Linq;
using OfficeOpenXml.Drawing.Slicer.Style;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.Tracing;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using static AutoMapper.Internal.CollectionMapperExpressionFactory;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace Coldairarrow.Business.Interface
{
    public class OL_EcommerceReturnInterfaceBusiness : Interface_BaseBusiness, IJob_Business, ITransientDependency
    {
        public List<OL_FilterDTO> Filters;
        public Base_InterfaceOption queryOption { get; set; }
        public Base_InterfaceOption insertOption { get; set; }
        public Base_InterfaceOption upDateOption { get; set; }
        public Base_InterfaceOption deleteOption { get; set; }

        public OL_EcommerceReturnInterfaceBusiness()
        {
            this.InterfaceName = "电商订单退货";
            //获取字段的映射关系
            tableField = GetMapField("editRow");
            //索引字段
            Keys = GetKeys("editRow");
            indexFields.Add(Keys.Where(X => X.Type == "K").First().Field);
            //查询过滤条件
            Filters = new List<OL_FilterDTO>();

            //数据库连接
            ConString = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
            SqlDb = (SqlServerHelper)DbHelperFactory.GetDbHelper(EFCore.Sharding.DatabaseType.SqlServer, ConString);

            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            this.queryOption = this.interfaceOption.Where(o => o.OperateType == "getFilterRows").First();//查询API配置
            this.insertOption = this.interfaceOption.Where(o => o.OperateType == "addRow").First();//新增API配置
            this.upDateOption = this.interfaceOption.Where(o => o.OperateType == "editRow").First();//更行API配置
            this.deleteOption = this.interfaceOption.Where(o => o.OperateType == "deleteRow").First();//删除API配置

            //查询执行前的事件
            BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //执行非查询请求中的事件
            OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;
        }


        /// <summary>
        /// 执行非查询请求中时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="noQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, NoQueryEventArgs noQueryEventArgs)
        {
            //API请求是否成功
            noQueryEventArgs.Success = noQueryEventArgs.Result["success"].ToString().ToBool();
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_BeforeQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //执行查询前添加过滤条件
            if (queryEventArgs.Page.Filters.IsNullOrEmpty() && !Filters.IsNullOrEmpty())
            {
                queryEventArgs.Page.Filters = Filters;
            }

        }

        /// <summary>
        /// 查询执行中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //是否查询完成
            if (queryEventArgs.Result["data"]["rows"].ToList().Count == 0)
            {
                queryEventArgs.Page.Complete = true;
            }
            //向总行中添加新的行
            queryEventArgs.Rows.AddRange(queryEventArgs.Result["data"]["rows"].ToList());
            //获取总页数
            queryEventArgs.Page.Total = queryEventArgs.Result["data"]["total"].ToString().ToInt();
            //获取查询成功标志
            queryEventArgs.Success = queryEventArgs.Result["success"].ToString().ToBool();
        }


        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async void ExecuteInterface()
        {

            try
            {

                //MSKU

                //获取One_Link SKU信息
                OL_LocalSKUInterfaceBusiness localSKU = new OL_LocalSKUInterfaceBusiness();
                localSKU.Filters.Clear();
                localSKU.Filters.Add(
               //13:>,14>=15:<,16<=
               new OL_FilterDTO() { ControlId = "", DataType = 15, SpliceType = 1, FilterType = 14, Value = "" }//FDATE字段过滤日开始700天前到现在的数据
           );
                List<LocalSKU> localSKUList = await localSKU.QueryAsync<LocalSKU>(localSKU.queryOption, localSKU.tableField, localSKU.SqlDb);


                //获取店铺
                OL_ShopInterfaceBusiness OL_Shop = new OL_ShopInterfaceBusiness();
                OL_Shop.Filters.Add(
            new OL_FilterDTO() { ControlId = "", DataType = 29, SpliceType = 1, FilterType = 8, Value = "" }
                //new OL_FilterDTO() { ControlId = "661d1c34387bc49b7a55d06e", DataType = 15, SpliceType = 1, FilterType = 14, Value = "2024-11-24" }
                );
                List<OL_Shop> shopList = OL_Shop.Query<OL_Shop>(OL_Shop.queryOption, OL_Shop.tableField, OL_Shop.SqlDb);
                shopList.ForEach(x =>
                {
                    //平台
                    List<AssTable> table = x.Platform_.ToObject<List<AssTable>>();
                    if (!table.IsNullOrEmpty() && table.Count > 0) x.Platform_ = table.IsNullOrEmpty() ? "" : table.First().sid;
                });



                string firstDate = DateTime.Now.AddDays(-queryOption.ExcInterval).ToString("yyyy-MM-dd");


                List<OL_EcommerceReturn> returnskLsit = new List<OL_EcommerceReturn>();



                List<OL_EcommerceReturn> sales = new List<OL_EcommerceReturn>();
                //易仓退货

                //小米

                //亚马逊退货
                sales = GetAMZReturnFBA(firstDate.ToDateTime().Date, localSKUList, shopList);
                returnskLsit.AddRange(sales);
                sales = GetAMZReturnFBM(firstDate.ToDateTime().Date, localSKUList, shopList);
                returnskLsit.AddRange(sales);
                //获取OZON退货数据
                sales = GetOZReturn(firstDate.ToDateTime().Date, localSKUList, shopList);
                returnskLsit.AddRange(sales);
                //获取WB退货数据
                sales = GetWBReturn(firstDate.ToDateTime().Date, localSKUList, shopList);
                returnskLsit.AddRange(sales);
                //获取YD退货数据
                sales = GetYDReturn(firstDate.ToDateTime().Date, localSKUList, shopList);
                returnskLsit.AddRange(sales);




                List<OL_EcommerceReturn> sourceData = new List<OL_EcommerceReturn>();
                sourceData = returnskLsit;



                //获取目标数据

                Filters.Clear();
                Filters.Add(
                //13:>,14>=15:<,16<=
                new OL_FilterDTO() { ControlId = "6915aadc3c333678d62b0a25", DataType = 15, SpliceType = 1, FilterType = 14, Value = firstDate }//FDATE字段过滤日开
            );
                List<OL_EcommerceReturn> targetData = await QueryAsync<OL_EcommerceReturn>(queryOption, tableField, SqlDb);

                targetData.ForEach(x =>
                {
                    //平台
                    List<AssTable> table = x.Platform.ToObject<List<AssTable>>();
                    if (!table.IsNullOrEmpty() && table.Count > 0) x.Platform = table.First().sid;
                    else x.Platform = "";
                    //店铺
                    table = x.Seller.ToObject<List<AssTable>>();
                    if (!table.IsNullOrEmpty() && table.Count > 0) x.Seller = table.First().sid;
                    else x.Seller = "";
                    //SKU
                    table = x.SKU.ToObject<List<AssTable>>();
                    if (!table.IsNullOrEmpty() && table.Count > 0) x.SKU = table.First().sid;
                    else x.SKU = "";
                    //MSKU
                    table = x.MSKU.ToObject<List<AssTable>>();
                    if (!table.IsNullOrEmpty() && table.Count > 0) x.MSKU = table.First().sid;
                    else x.MSKU = "";

                });


                var ww = targetData.GroupBy(x => x).Where(x => x.Count() > 1);
                if (this.State > 0 && sourceData.Count > 0)
                {
                    //更新
                    #region
                    List<OL_EcommerceReturn> updataItem = sourceData.Intersect(targetData, new ComparerFromKeys<OL_EcommerceReturn>(Keys, "RowId")).ToList();//获取交集(更新项)
                    List<OL_RowDTO> updataData = ConvertOL_Row(updataItem, tableField);//需要更新的数据集合
                    ExecuteNoQuery<OL_RowDTO>(updataData, upDateOption, SqlDb);//执行更新
                    #endregion

                    //新增
                    #region
                    List<OL_EcommerceReturn> insertItem = sourceData.Except(targetData, new ComparerFromKey<OL_EcommerceReturn>(indexFields.First(), "RowId")).ToList();//获取源数据对目标数据的差集(新增项)
                    List<OL_RowDTO> insertData = ConvertOL_Row(insertItem, tableField);//需要新增的数据集合
                    ExecuteNoQuery<OL_RowDTO>(insertData, insertOption, SqlDb);//执行插入行
                    #endregion

                    //删除
                    #region
                    List<OL_EcommerceReturn> deleteItem = targetData.Except(sourceData, new ComparerFromKey<OL_EcommerceReturn>(indexFields.First(), "RowId")).ToList();//获取目标数对据源数据的差集(删除项)
                    List<OL_EcommerceReturn> repeatItem = targetData.GroupBy(x => x.GetPropertyValue(indexFields.First())).Where(x => x.Count() > 1).Select(x => x.FirstOrDefault()).ToList();
                    //将重复的项也一起加入删除的列表
                    deleteItem.AddRange(repeatItem);
                    //筛选出删除列表中重复的项
                    var temp = deleteItem.GroupBy(x => x.GetPropertyValue(indexFields.First())).Where(x => x.Count() > 1).Select(x => x.FirstOrDefault()).ToList();
                    deleteItem.AddRange(temp);
                    List<OL_RowDTO> deleteData = ConvertOL_Row(deleteItem, tableField);//需要删除的数据集合
                    ExecuteNoQuery<OL_RowDTO>(deleteData, deleteOption, SqlDb);//执行删除行
                    #endregion

                    //同步数据库
                    SqlDBInterfaceBusiness sqlDBInterface = new SqlDBInterfaceBusiness(Keys);
                    sqlDBInterface.ExecuteInterface<OL_EcommerceReturn>(sourceData, "SD_OL_EcommerceReturn", $"WHERE CONVERT(date,ReturnDate) >= '{firstDate}'");
                }
            }


            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }



        public List<OL_EcommerceReturn> GetOZReturn(DateTime firstDate, List<LocalSKU> localSKUList, List<OL_Shop> shopList)
        {
            List<OL_EcommerceReturn> dataList = new List<OL_EcommerceReturn>();
            this.SqlDb._conStrings[0] = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
            //订单数据
            List<FBOFBSReturns> orderList = this.SqlDb.GetListBySql<FBOFBSReturns>(@$"SELECT * FROM SD_OZ_FBOFBSReturns WHERE CONVERT(date,return_date) >= '{firstDate}'");
            //产品编码
            List<RE_Product> prdList = this.SqlDb.GetListBySql<RE_Product>(@$"SELECT * FROM SD_RE_Product");

            //类型转换
            foreach (var item1 in orderList)
            {
                OL_EcommerceReturn row = new OL_EcommerceReturn();

                row.ReturnOrder = item1.order_number;
                row.Order = item1.order_number;
                row.ReturnDate = item1.return_date;
                row.State = "";
                row.OriginallyState = item1.status_sys_name;
                //店铺平台
                var s = shopList.Where(x => x.ID == item1.company_id);
                if (!s.IsNullOrEmpty())
                {
                    row.Seller = s.First().RowId;
                    row.Platform = s.First().Platform_;
                }
                row.ProductNumber = item1.offer_id;
                //仓库产品代码
                var p = prdList.Where(x => x.reference_no == item1.offer_id);
                if (!p.IsNullOrEmpty())
                {
                    row.StockNumber = p.First().product_sku;
                }
                row.SKU = "";
                row.Qty = item1.quantity.ToInt();
                row.ProductName = item1.name;
                //平台品类
                var t1 = GetEURPrdTypeAndBrand(item1.offer_id);
                row.ProductType = t1.Item1;
                row.ProductBrand = t1.Item2;


                row.Price = (decimal)item1.price.ToDouble();
                row.Commission = (decimal)item1.commission.ToDouble();
                row.Currency = item1.price_currency_code;
                row.SellerId = item1.company_id;
                row.ReturnReason = "";
                row.UserComments = "";
                row.ID = item1.id;
                dataList.Add(row);
            }
            return dataList;
        }

        public List<OL_EcommerceReturn> GetWBReturn(DateTime firstDate, List<LocalSKU> localSKUList, List<OL_Shop> shopList)
        {
            List<OL_EcommerceReturn> dataList = new List<OL_EcommerceReturn>();
            this.SqlDb._conStrings[0] = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
            //订单数据
            List<BuyersReturn> orderList = this.SqlDb.GetListBySql<BuyersReturn>(@$"SELECT * FROM SD_WB_BuyersReturn WHERE CONVERT(date,dt) >= '{firstDate}'");
            //产品编码
            List<RE_Product> prdList = this.SqlDb.GetListBySql<RE_Product>(@$"SELECT * FROM SD_RE_Product");

            //类型转换
            foreach (var item1 in orderList)
            {
                OL_EcommerceReturn row = new OL_EcommerceReturn();

                row.ReturnOrder = item1.id;
                row.Order = item1.srid;
                row.ReturnDate = item1.dt.ToDateTime().ToString();
                row.State = "";
                row.OriginallyState = item1.status;
                //店铺平台
                var s = shopList.Where(x => x.ID == "Wildberries");
                if (!s.IsNullOrEmpty())
                {
                    row.Seller = s.First().RowId;
                    row.Platform = s.First().Platform_;
                }
                row.ProductNumber = item1.vendorCode;
                //仓库产品代码
                var p = prdList.Where(x => x.reference_no == item1.vendorCode);
                if (!p.IsNullOrEmpty())
                {
                    row.StockNumber = p.First().product_sku;
                }
                row.SKU = "";
                row.Qty = 1;
                row.ProductName = item1.imt_name;
                //平台品类
                var t1 = GetEURPrdTypeAndBrand(item1.vendorCode);
                row.ProductType = t1.Item1;
                row.ProductBrand = t1.Item2;


                row.Price = (decimal)item1.price.ToDouble();
                row.Commission = 0;
                row.Currency = "RUB";
                row.SellerId = "Wildberries";
                row.ReturnReason = "";
                row.UserComments = item1.user_comment;
                row.Note = item1.wb_comment;
                row.ID = item1.id;
                dataList.Add(row);
            }
            return dataList;
        }


        public List<OL_EcommerceReturn> GetYDReturn(DateTime firstDate, List<LocalSKU> localSKUList, List<OL_Shop> shopList)
        {
            List<OL_EcommerceReturn> dataList = new List<OL_EcommerceReturn>();
            this.SqlDb._conStrings[0] = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
            //订单数据
            List<YDReturnsDTO.Returns> orderList = this.SqlDb.GetListBySql<YDReturnsDTO.Returns>(@$"SELECT * FROM SD_YD_Returns WHERE CONVERT(date,creationDate) >= '{firstDate}'");
            //产品编码
            List<RE_Product> prdList = this.SqlDb.GetListBySql<RE_Product>(@$"SELECT * FROM SD_RE_Product");

            //类型转换
            foreach (var item1 in orderList)
            {
                OL_EcommerceReturn row = new OL_EcommerceReturn();

                row.ReturnOrder = item1.orderId;
                row.Order = item1.orderId;
                row.ReturnDate = item1.creationDate;
                row.State = "";
                row.OriginallyState = item1.shipmentStatus;
                //店铺平台
                var s = shopList.Where(x => x.ID == item1.SellerId);
                if (!s.IsNullOrEmpty())
                {
                    row.Seller = s.First().RowId;
                    row.Platform = s.First().Platform_;
                }
                row.ProductNumber = item1.items_shopSku;
                //仓库产品代码
                var p = prdList.Where(x => x.reference_no == item1.items_shopSku);
                if (!p.IsNullOrEmpty())
                {
                    row.StockNumber = p.First().product_sku;
                }
                row.SKU = "";
                row.Qty = item1.items_count.ToInt();
                row.ProductName = "";
                //平台品类
                var t1 = GetEURPrdTypeAndBrand(item1.items_shopSku);
                row.ProductType = t1.Item1;
                row.ProductBrand = t1.Item2;


                row.Price = (decimal)item1.amount_value.ToDouble();
                row.Commission = 0;
                row.Currency = item1.amount_currencyId;
                row.SellerId = item1.SellerId;
                row.ReturnReason = item1.decisions_reasonType;
                row.UserComments = item1.decisions_comment;
                row.Note = "";
                row.ID = item1.ID_;
                dataList.Add(row);
            }
            return dataList;
        }


        private (string, string) GetEURPrdTypeAndBrand(string code)
        {
            string type = "";
            string brand = "";
            if (code.Contains("TIH"))
            {  //品类
                type = "电磁炉";

                //品牌
                brand = "Tecasa";
            }
            else if (code.Contains("TCH"))
            {
                //品类
                type = "电陶炉";

                //品牌
                brand = "Tecasa";
            }
            else if (code.Contains("SPF01"))
            {
                //品类
                type = "热水器";

                //品牌
                brand = "Superflame";
            }
            else if (code.Contains("SPF02"))
            {
                //品类
                type = "热水器";

                //品牌
                brand = "Mizudo";
            }
            else if (code.Contains("CB."))
            {
                //品类
                type = "壁挂炉";

                //品牌
                brand = "Mizudo";
            }
            else
            {
                //品类
                type = "";
                //品牌
                brand = "";
            }
            return (type, brand);

        }

        public List<OL_EcommerceReturn> GetAMZReturnFBA(DateTime firstDate, List<LocalSKU> localSKUList, List<OL_Shop> shopList)
        {
            List<OL_EcommerceReturn> dataList = new List<OL_EcommerceReturn>();
            this.SqlDb._conStrings[0] = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
            //订单数据
            List<FBAReturnOrder> orderList = this.SqlDb.GetListBySql<FBAReturnOrder>(@$"SELECT * FROM SD_LX_FBAReturnOrder WHERE CONVERT(date,return_date_locale) >= '{firstDate}'");

            //类型转换
            foreach (var item1 in orderList)
            {
                OL_EcommerceReturn row = new OL_EcommerceReturn();

                row.ReturnOrder = item1.order_id;
                row.Order = item1.order_id;
                row.ReturnDate = item1.return_date_locale;
                row.State = "";
                row.OriginallyState = item1.status;
                //店铺平台
                var s = shopList.Where(x => x.ID == item1.sid);
                if (!s.IsNullOrEmpty())
                {
                    row.Seller = s.First().RowId;
                    row.Platform = s.First().Platform_;
                }
                row.ProductNumber = item1.sku;
                //仓库产品代码

                row.StockNumber = item1.fnsku;
                row.SKU = "";
                row.Qty = item1.quantity.ToInt();
                row.ProductName = "";
               


                row.Price = 0;
                row.Commission = 0;
                row.Currency = "";
                row.SellerId = item1.sid;
                row.ReturnReason = item1.reason;
                row.UserComments = "";
                row.Note = "";
                row.ID = item1.id;
                dataList.Add(row);
            }
            return dataList;
        }
        public List<OL_EcommerceReturn> GetAMZReturnFBM(DateTime firstDate, List<LocalSKU> localSKUList, List<OL_Shop> shopList)
        {
            List<OL_EcommerceReturn> dataList = new List<OL_EcommerceReturn>();
            this.SqlDb._conStrings[0] = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
            //订单数据
            List<FBMReturnOrder> orderList = this.SqlDb.GetListBySql<FBMReturnOrder>(@$"SELECT * FROM SD_LX_FBMReturnOrder WHERE CONVERT(date,return_date) >= '{firstDate}'");

            //类型转换
            foreach (var item1 in orderList)
            {
                OL_EcommerceReturn row = new OL_EcommerceReturn();

                row.ReturnOrder = item1.order_id;
                row.Order = item1.order_id;
                row.ReturnDate = item1.return_date;
                row.State = "";
                row.OriginallyState = item1.return_status;
                //店铺平台
                var s = shopList.Where(x => x.ID == item1.sid);
                if (!s.IsNullOrEmpty())
                {
                    row.Seller = s.First().RowId;
                    row.Platform = s.First().Platform_;
                }
                row.ProductNumber = item1.seller_sku;
                //仓库产品代码

                row.StockNumber = "";
                row.SKU = "";
                row.Qty = item1.return_quantity;
                row.ProductName = item1.local_name;



                row.Price = item1.refunded_amount.IsNullOrEmpty()?0:(decimal)item1.refunded_amount.ToDouble();
                row.Commission = item1.label_cost.IsNullOrEmpty() ? 0 : (decimal)item1.label_cost.ToDouble();
                row.Currency = item1.currency_code;
                row.SellerId = item1.sid;
                row.ReturnReason = item1.return_reason;
                row.UserComments = "";
                row.Note = "";
                row.ID = item1.id;
                dataList.Add(row);
            }
            return dataList;
        }
        /// <summary>
        /// 将源数据根据字典映射关系转换成OL_RowDTO
        /// </summary>
        /// <typeparam name="T">源数据</typeparam>
        /// <param name="sourceData">源数据</param>
        /// <param name="map">Key为目标字段名称，Value为源字段名称</param>
        /// <returns></returns>
        public List<OL_RowDTO> ConvertOL_Row<T>(List<T> sourceData, Dictionary<string, string> map)
        {
            List<OL_RowDTO> list = new List<OL_RowDTO>();
            object rowId;
            foreach (var item in sourceData)
            {
                rowId = item.GetPropertyValue("RowId");
                //需要新增的数据
                OL_RowDTO row = new OL_RowDTO() { RowId = rowId.IsNullOrEmpty() ? null : rowId.ToString(), Controls = new List<Control>() };
                foreach (var c in map)
                {
                    //获取字段的键值做判断
                    var field = Keys.Where(x => x.TField == c.Key).ToList();
                    string isKey = "";
                    if (field.Count > 0) isKey = field.First().Type;
                    //判断对象的字段是否存在
                    if (item.ContainsProperty(c.Value) && isKey != "N")
                    {
                        //存在则添加数据
                        row.Controls.Add(new Control() { ControlId = c.Key, Value = item.GetPropertyValue(c.Value) });
                    }
                }
                list.Add(row);
            }
            return list;
        }
        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }

}
